package com.pandora.common.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.SecureRandom;
import java.util.Random;
import java.util.UUID;

import com.pandora.common.exception.EduException;
import com.pandora.framework.constant.Constants;
import com.pandora.framework.util.LogUtils;

/**
 * 字符串操作工具类
 * 
 * @author JingChenglong 2017/12/15 18:28
 *
 */
public class StringUtils {

	public static final double MONEY_MIN = 0.01D;
	public static final double MONET_MAX = 1000000000.00D;

	private static SecureRandom secureRand = null;
	private static Random rand = null;

	private static String localhost = "";

	static {
		secureRand = new SecureRandom();
		rand = new Random(secureRand.nextLong());
		localhost = WebUtils.getLocalHost();
	}

	public static boolean isEmpty(String str) {

		return ((str == null) || (str.trim().length() == 0));
	}

	/**
	 * 判断字符串是否为半角字符集
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isHalfAngle(String str) {

		str = nullToStrTrim(str);
		return str.length() == getWordLength(str);
	}

	public static boolean isInvalid(String str) {
		return (isEmpty(str) || Constants.UNKNOWN.equalsIgnoreCase(str.trim())
				|| Constants.STR_NULL.equalsIgnoreCase(str.trim())
				|| Constants.STR_UNDEFINED.equalsIgnoreCase(str.trim()));
	}

	public static boolean haveEmpty(String... strs) {
		for (String str : strs) {
			if (isEmpty(str)) {
				return true;
			}
		}
		return false;
	}

	public static boolean isNotEmpty(String str) {

		return ((str != null) && (str.trim().length() > 0));
	}

	public static boolean haveNotEmpty(String... strs) {
		for (String str : strs) {
			if (isEmpty(str)) {
				return false;
			}
		}
		return true;
	}

	public static boolean haveEmpty(Object... objs) {
		for (Object obj : objs) {
			if (obj == null) {
				return true;
			}
		}
		return false;
	}

	public static boolean isBlank(String str) {
		if (isEmpty(str)) {
			return true;
		}
		for (int i = 0; i < str.length(); i++) {
			if (Character.isWhitespace(str.charAt(i))) {
				return false;
			}
		}
		return false;
	}

	public static String nullToStr(String str) {

		return str == null ? "" : str;
	}

	public static String nullToStrTrim(String str) {

		return str == null ? "" : str.trim();
	}

	public static int nullToIntZero(String str) {

		str = isEmpty(str) ? "0" : str;
		return Integer.valueOf(str.trim(), 10);
	}

	public static double nullToDoubleZero(String str) {

		str = isEmpty(str) ? "0.00" : str;
		return Double.valueOf(str.trim());
	}

	public static long nullToLongZero(String str) {

		str = isEmpty(str) ? "0" : str;
		return Long.valueOf(str.trim(), 10);
	}

	public static boolean nullToBoolean(String str) {

		return isEmpty(str) ? false : Boolean.valueOf(str.trim());
	}

	public static String nullToUnKnown(String str) {

		return isEmpty(str) ? Constants.UNKNOWN : str.trim();
	}

	public static String encodeHTML(String str) {
		if (isEmpty(str)) {
			return "";
		}
		char[] content = new char[str.length()];
		str.getChars(0, str.length(), content, 0);
		StringBuffer sb = new StringBuffer();

		for (int i = 0; i < content.length; i++) {
			switch (content[i]) {
			case '<':
				sb.append("&lt;");
				break;
			case '>':
				sb.append("&gt;");
				break;
			case '&':
				sb.append("&amp;");
				break;
			case '"':
				sb.append("&quot;");
				break;
			case '\'':
				sb.append("&#039;");
				break;
			default:
				sb.append(content[i]);
				break;
			}
		}

		return sb.toString();
	}

	/**
	 * 去除字符串中的空白字符
	 * 
	 * @param str
	 * @return
	 */
	public static String removeBlank(String str) {
		// TODO 去除字符串中的空白字符
		if (isEmpty(str)) {
			return str;
		}
		str = str.replaceAll("\n", "");
		str = str.replaceAll("\t", "");
		str = str.replaceAll(" ", "");
		return nullToStrTrim(str);
	}

	/**
	 * 校验字符串的长度
	 * 
	 * @param str
	 * @param maxLength
	 * @param code
	 * @throws EduException
	 */
	public static void checkMaxWordLength(String str, int maxLength, int code) throws EduException {
		if (isNotEmpty(str) && getWordLength(str) > maxLength) {
			throw new EduException(code);
		}
	}

	/**
	 * 获取字符串的绝对长度，一个中文字符长度为2
	 * 
	 * @param str
	 * @return
	 */
	public static int getWordLength(String str) {

		return nullToStr(str).replaceAll("[^\\x00-\\xff]", "**").length();
	}

	public static String getUUID() {

		return UUID.randomUUID().toString();
	}

	/**
	 * 根据参数给定范围获取整数随机数
	 * 
	 * @param accuracy
	 * @return
	 */
	public static int getRandom(int accuracy) {

		return (int) (Math.random() * accuracy);
	}

	/**
	 * 使用给定字符串中的字符生成指定长度的随机字符串
	 * 
	 * @param randString
	 * @param length
	 * @return
	 */
	public static String getRandom(String randString, int length) {
		if (length < 0) {
			LogUtils.logError(CommonUtils.getTraceInfo() + ";IllegalArguments :" + length);
			return "";
		}
		if (isEmpty(randString) || length == 0) {
			return "";
		}

		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			sb.append(randString.charAt(rand.nextInt(randString.length())));
		}
		return sb.toString();
	}

	public static String getRawRandom() {

		String str = MD5Utils
				.md5(getUUID() + System.currentTimeMillis() + getRandom(999999999) + rand.nextLong() + localhost);
		return str.toLowerCase();
	}

	public static String getRawRandom(String string) {

		String str = MD5Utils.md5(
				getUUID() + System.currentTimeMillis() + getRandom(999999999) + rand.nextLong() + localhost + string);
		return str.toLowerCase();
	}

	public static String getRandom() {

		String str = MD5Utils.md5(getUUID() + System.currentTimeMillis() + getRandom(999999999) + rand.nextLong());
		return str.toLowerCase();
	}

	public static String getRandom(String string) {

		String str = MD5Utils
				.md5(getUUID() + System.currentTimeMillis() + getRandom(999999999) + rand.nextLong() + string);
		return str.toLowerCase();
	}

	public static String decode(String str) {

		return decode(str, Constants.ENCODEING_DEFAULT);
	}

	public static String decode(String str, String enc) {

		if (isEmpty(str)) {
			return "";
		}

		try {
			str = URLDecoder.decode(str, enc);
		} catch (UnsupportedEncodingException e) {
			LogUtils.logError(CommonUtils.getTraceInfo() + e.getMessage());
		}

		return str;
	}

	/**
	 * 去除字符串首位和末尾的指定字符
	 * 
	 * @param str
	 * @param charStr
	 * @return
	 */
	public static String subStartAndEndChar(String str, String charStr) {

		if (isEmpty(str) || isEmpty(charStr)) {
			return str;
		}

		while (str.startsWith(charStr)) {
			str = str.substring(1);
		}
		while (str.endsWith(charStr)) {
			str = str.substring(0, str.length() - 1);
		}

		return nullToStrTrim(str);
	}

	/**
	 * 获取字符串绝对长度
	 * 
	 * @param resContent
	 * @return
	 */
	public static int getRealLength(String str) {

		return getRealLength(str, Constants.ENCODEING_DEFAULT);
	}

	public static int getRealLength(String str, String charset) {

		str = nullToStrTrim(str);

		if (isEmpty(str)) {
			return 0;
		}

		try {
			return str.getBytes(charset).length;
		} catch (UnsupportedEncodingException e) {
			LogUtils.logError(CommonUtils.getTraceInfo() + e.getMessage());
			return 0;
		}
	}

	// TODO 研究该方法
	public static String byte2hex(byte[] bArr) {

		String str = "";
		String stmp = "";

		for (byte b : bArr) {
			stmp = Integer.toHexString(b & 0XFF);
			if (stmp.length() == 1) {
				str += "0";
			}
			str += stmp;
		}
		return str.toLowerCase();
	}
}